package com.TripMate.system.AI;

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.engineio.client.transports.WebSocket;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static java.util.Collections.singletonMap;

@Slf4j
public class MyWebSocket {
    private final String webSocketUrl = "wss://wss.lke.cloud.tencent.com"; // websocket 服务器的 URL
    private final String path = "/v1/qbot/chat/conn/"; // 服务路径
    private String finalResponse = ""; // 用于存储最终回复内容

    public String webSocketInvoke(String content, String sid, String reqId) {
        Token getToken = new Token();
        String token = getToken.getWsToken();
        System.out.println("token:" + token);

        CountDownLatch latch = new CountDownLatch(1);

        try {
            IO.Options options = IO.Options.builder().setQuery("EIO=4").setPath(path)  // path需要以'/'开头
                    .setTransports(new String[]{WebSocket.NAME}).setAuth(singletonMap("token", token)).setTimeout(6000).build();
            // 创建 Socket.IO 客户端实例
            Socket socket = IO.socket(webSocketUrl, options);

            // 监听连接成功事件
            socket.on(Socket.EVENT_CONNECT, args1 -> log.info("EVENT_CONNECT: " + Arrays.toString(args1)));

            // 监听连接错误事件
            socket.on(Socket.EVENT_CONNECT_ERROR, args2 -> {
                System.out.println("EVENT_CONNECT_ERROR: " + Arrays.toString(args2));
                // 如果连接失败，可能需要更新auth，再发起连接
                options.auth.put("token", getToken.getWsToken());
                socket.disconnect().connect();
            });

            // 监听连接断开事件
            socket.on(Socket.EVENT_DISCONNECT, args3 -> System.out.println("EVENT_DISCONNECT: " + Arrays.toString(args3)));

            // 监听reply事件
            socket.on("reply", args4 -> {
                if (args4.length > 0) {
                    JSONObject reply = (JSONObject) args4[0];

                    try {
                        JSONObject payload = reply.getJSONObject("payload");
                        boolean isFromSelf = payload.getBoolean("is_from_self");
                        boolean isFinal = payload.getBoolean("is_final");
                        String respContent = payload.getString("content");
                        if (isFromSelf) {
                            System.out.println("Received reply, is_from_self, content: " + respContent);
                        } else if (isFinal) {
                            System.out.println("Received reply, is_final, content: " + respContent);
                            // 将最终回复内容保存到类变量中
                            finalResponse = respContent;
                            // 释放锁
                            latch.countDown();
                            socket.disconnect(); // 断开连接
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    log.info("Received reply, but args4.length <= 0");
                }
            });

            // 监听error事件
            socket.on("error", args5 -> {
                log.info("Received error: " + Arrays.toString(args5));
            });

            socket.connect();
            JSONObject payload = new JSONObject();
            payload.put("request_id", reqId);
            payload.put("content", content);
            payload.put("session_id", sid);
            JSONObject data = new JSONObject();
            data.put("payload", payload);
            // 发送消息
            socket.emit("send", data);

            // 等待回复，超时时间为12秒
            boolean isTimeout = !latch.await(200, TimeUnit.SECONDS);

            if (isTimeout) {
                finalResponse = "请求超时，请重新尝试。";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return finalResponse; // 返回最终回复内容
    }
}
